package com.jinunn.yygh.utils;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author : JinDun
 * @date : 2021/4/25 21:40
 */
@Slf4j
public class ExcelUtils {

    public static void writeExcel(HttpServletResponse response, List<?> list,String fileName,String sheetName){
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("导出数据为空");
        }
        if (StringUtils.isEmpty(fileName)) {
            fileName = String.valueOf(System.currentTimeMillis());
        }
        if (StringUtils.isEmpty(sheetName)) {
            sheetName = "Sheet1";
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition",
                "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8),
                        StandardCharsets.ISO_8859_1) + ".xlsx");
        try {
            EasyExcel.write(response.getOutputStream(), list.get(0).getClass())
                    .autoCloseStream(Boolean.FALSE)
                    .sheet(sheetName)
                    .doWrite(list);
        } catch (IOException e) {
            log.error("导出excel异常!");
            e.printStackTrace();
        }
    }
}
